/**
 * 线图生成类
 * @param parent 父组件dom对象
 * @param config 图形的配置对象
 * <br>
 * <br>dataset : Y轴数据数组，二维数组
 * <br>xMarks : X轴数据数组，一维数组
 * <br>seriesNames : 系列名称，数组
 * <br>seriesColors : 系列颜色，数组
 * <br>title : 标题,字符串
 * <br>subtitle : 子标题,字符串
 * <br>udfMaxMinEnable : 是否自定义最大最小值，true标识启用，则需设置maxXdata, minXdata, maxXLimit, minXLimit,maxYdata, minYdata, maxYLimit, minYLimit
 * <br>udfOptions:自定义属性{maxXdata, minXdata, maxXLimit, minXLimit,maxYdata, minYdata, maxYLimit, minYLimit}
 * <br>showRefLine:是否显示基准直线
 * <br>lineColor:自定义基准线线颜色，当showRefLine为true时启用
 * <br>lineStyle:自定义基准线线型，当showRefLine为true时启用
 * <br>xyDataSet:自定义基准线起点和终点，如[{x:0,y:0},{x:1,y:1}]，当showRefLine为true时启用
 */

window.ScatterChart = function ScatterChart(parent, config) {
	config = config || {};
	var container = $(parent);
	
	var dataset = config.dataset || [];
	
	var symbolTypes = config.symbolTypes || ["circle"]; 
	
	
	//最大值，最小值，最大限制值，最小限制值
	var maxXdata, minXdata, maxXLimit, minXLimit;
	var maxYdata, minYdata, maxYLimit, minYLimit;
	if (config.udfMaxMinEnable){
		maxXdata = config.udfOptions.maxXdata;
		minXdata = config.udfOptions.minXdata;
		maxXLimit = config.udfOptions.maxXLimit;
		minXLimit = config.udfOptions.minXLimit;
		maxYdata = config.udfOptions.maxYdata;
		minYdata = config.udfOptions.minYdata;
		maxYLimit = config.udfOptions.maxYLimit;
		minYLimit = config.udfOptions.minYLimit;
	}
	
	
	var xAxisTitle = config.xAxisTitle || ('X'+TempoUtils.locale("mine.zhou"));
	var yAxisTitle = config.yAxisTitle || ('Y'+TempoUtils.locale("mine.zhou"));
	
	var showLegend = config.showLegend == null ? true : config.showLegend;
	var showRefLine = config.showRefLine == null ? false : config.showRefLine;
	//轴标签的大长度
	var legendLabelMaxLength = 6;
	
 	if(dataset.length == 0) {
 		return;
 	}
 	
 	var yTicksLength = 10;
	var maxLabelLength = 10;
	
 	var _series = []; //保存一个系列散点对象
 	var xMarks = config.xMarks || [];//X轴的标签
 	var seriesNames = config.seriesNames || []; //保存系列名称
 	var seriesColors = config.seriesColors || ["#F00","#09F","#0F0"];
 	var w = container.width();
 	var h = container.height();
 	var padding=40;
 	var currentLineNum=0;
 	
 	//用一个变量存储标题和副标题的高度，如果没有标题什么的，就为0
 	var head_height = padding;
 	var title = config.title || "";
 	var subTitle= config.subtitle || "";
 	 
 	//用一个变量计算底部的高度，如果不是多系列，就为0
 	var foot_height = padding;
 	var left_padding = padding;
 	
 	//保存数组长度，也就是系列的个数
 	currentLineNum = dataset.length;
 	 
 	//定义画布
 	var svg = d3.select(parent).append("svg")
 		.attr("width",w).attr("height",h);
 	 
 	//添加背景
 	svg.append("g").append("rect")
	 	.attr("x",0).attr("y",0)
	 	.attr("width",w).attr("height",h)
	 	.style("fill","#FFF").style("stroke-width",2).style("stroke","#E7E7E7");
 	 
 	//添加标题
 	if(title!="")
 	{
	 	svg.append("g").append("text").text(title).attr("class","gl_title")
	 		.attr("x",w/2).attr("y",head_height);
	 	 
	 	head_height+=30;
 	}
 	 
 	//添加副标题
 	if(subTitle!="")
 	{
	 	svg.append("g").append("text").text(subTitle).attr("class","gl_subTitle")
	 		.attr("x",w/2).attr("y",head_height);
	 	 
	 	head_height+=20;
 	}
 	// 若不是自定义最大最小值，则需要更新最大最小值
 	if (!config.udfMaxMinEnable){
 		updateMaxMin(dataset);
 	}

 	if(showLegend) {
 		//添加图例
 		var legend=svg.append("g");
 		addLegend();
 		//图例的预留位置
 		head_height += 25;
 	}

	//x轴的定义域
	var xDomain = [minXLimit, maxXLimit];
	
 	//为X标题预留位置
	foot_height += 16;
	left_padding = left_padding + 16;
	
	var yTitle = svg.append("text").text(yAxisTitle).attr("text-anchor", "middle")
		.attr("y", padding + "px")
		.attr("dy", "-1em")
		.attr("x", -(head_height + (h - head_height - foot_height) / 2) + "px")
		.attr("transform", "rotate(-90)")
		.attr("class", "gl_axis_title");
	
	
	//纵坐标轴比例尺
 	var yScale = d3.scale.linear()
 		.domain([minYLimit, maxYLimit]).range([h - foot_height, head_height]);
 	
 	var yTicks = yScale.ticks(yTicksLength);
 	if(yTicks.length > 0) {
 		var maxYLabelLength = d3.max([(yTicks[0] + "").length, (yTicks[yTicks.length - 1] + "").length]);
 		//假设一个数字是7像素
 		left_padding += maxYLabelLength * 7;
 	}
 	
 	var xTitle = svg.append("text").text(xAxisTitle).attr("text-anchor", "middle")
	.attr("x", (left_padding + (w - left_padding - padding) / 2) + "px").attr("y", (h - foot_height + 16) + "px").attr("dy", "2em").attr("class", "gl_axis_title");

 	
 	//横坐标轴比例尺
 	var xScale = d3.scale.linear()
 		.domain(xDomain).range([left_padding, w - padding]);
 	 
 	//定义横轴网格线
 	var xInner = d3.svg.axis()
	 	.scale(xScale)
	 	.tickSize(-(h - head_height - foot_height),0,0)
	 	.tickFormat("")
	 	.orient("bottom");
 	 
 	//添加横轴网格线
 	var xInnerBar=svg.append("g")
	 	.attr("class","gl_inner_line")
	 	.attr("transform", "translate(0," + (h - foot_height) + ")")
	 	.call(xInner);
 	 
 	//定义纵轴网格线
 	var yInner = d3.svg.axis().scale(yScale)
	 	.tickSize(-(w - left_padding - padding),0,0)//总宽度减去左侧宽度和右侧宽度
	 	.tickFormat("")
	 	.orient("left")
	 	.ticks(yTicksLength);
 	 
 	//添加纵轴网格线
 	var yInnerBar=svg.append("g").attr("class", "gl_inner_line")
	 	.attr("transform", "translate("+left_padding+",0)")
	 	.call(yInner);
 	 
 	//定义横轴
 	var xAxis = d3.svg.axis().scale(xScale).orient("bottom");
 	 
 	//添加横坐标轴
 	var xBar=svg.append("g")
	 	.attr("class","gl_axis")
	 	.attr("transform", "translate(0," + (h - foot_height) + ")")
	 	.call(xAxis);
 	//通过编号获取对应的横轴标签
 	xBar.selectAll("text").text(function(d, i){
 		//最大3位小数
 		return Math.round(parseFloat(d) * 1000) / 1000;
 	});
 	 
 	//定义纵轴
 	var yAxis = d3.svg.axis()
	 	.scale(yScale)
	 	.orient("left")
	 	.ticks(yTicksLength);
 	 
 	//添加纵轴
 	var yBar=svg.append("g")
	 	.attr("class", "gl_axis")
	 	.attr("transform", "translate("+left_padding+",0)")
	 	.call(yAxis);
 	
 	if (showRefLine) {
 	 	var xyDataSet = [];
 	 	if (config.xyDataSet){
 	 		xyDataSet = config.xyDataSet;
 	 	} else {
 	 		var startPoint = {};
 	 		var minVal = parseFloat(minYLimit < minXLimit ?　minXLimit : minYLimit);
 	 		startPoint.x = minVal;
 	 		startPoint.y = minVal;
 	 		var maxVal = parseFloat(maxXdata > maxYdata ? maxXdata:maxYdata);
 	 		var endPoint = {};
 	 		endPoint.x = maxVal;
 	 		endPoint.y = maxVal;
 	 		xyDataSet.push(startPoint);
 	 		xyDataSet.push(endPoint);
 	 	}
 		var line=d3.svg.line()
 		.x(function(d){
 			return xScale(d.x);
 		})
 		.y(function(d){
 			return yScale(d.y);
 		});
 		// 线颜色
 		var lineColor = seriesColors[0];
 		if (config.lineColor){
 			lineColor = config.lineColor;
 		}
 		// 线型，默认实线
 		var dasharray = 0;
 		if (config.lineStyle && config.lineStyle == "dashed"){
 			// 虚线
 			dasharray = 5;
 		}
 		var path=svg.append('path')
 		.attr('fill','none')
 		.attr('stroke-width',1)
 		.style("stroke-opacity", 0.9)
 		.attr("stroke-dasharray",dasharray)
 		.attr('stroke',lineColor)
 		.attr('d',line(xyDataSet));
 	}
	
 	//添加折线
 	_series=[];
 	for(i=0;i<currentLineNum;i++)
 	{
	 	var newLine=new CrystalScatterObject();
	 	newLine.init(i);
	 	_series.push(newLine);
 	}
 	
 	//定义折线类
	function CrystalScatterObject()
	{
		this.group=null;
		this.path=null;
		this.oldData=[];
		 
		this.init=function(id)
		{
			var arr = dataset[id];
			this.group=svg.append("g");
			
			var symbolDealer = d3.svg.symbol();
			symbolDealer.size(36);
			symbolDealer.type(symbolTypes[id % symbolTypes.length]);
			
			this.group.selectAll("path").data(arr).enter().append("path")
			.attr("d", function(d) {
				return symbolDealer();
			})
			.style("stroke-width", 2)
			.style("stroke", seriesColors[id % seriesColors.length])
			.style("stroke-opacity", 0.9)
			.attr("transform", function(d) {
				return "translate(" + xScale(d[0]) + "," + yScale(d[1]) + ")";
			})
			.attr("fill",seriesColors[id % seriesColors.length]).append("title").text(function(d) {
				var seriesLine = null;
				var sn = seriesNames[id];
				if(sn != null && sn != "<NULL>") {
					seriesLine = sn;
				}
				return (seriesLine == null ? "" : (seriesLine + "\n")) + "(" + d[0] + ", " + d[1] + ")";
			});
			
			this.oldData=arr;
		};
		 
		//动画初始化方法
		this.movieBegin=function(id)
		{
			var arr=dataset[i];
			//补足/删除路径
			var olddata=this.oldData;
			var line= d3.svg.line()
				.x(function(d,i){if(i>=olddata.length) return w-padding; else return xScale(i);})
				.y(function(d,i){if(i>=olddata.length) return h-foot_height; else return yScale(olddata[i]);});
			 
			//路径初始化
			this.path.attr("d",line(arr));
			 
			//截断旧数据
			var tempData=olddata.slice(0,arr.length);
			var circle=this.group.selectAll("circle").data(tempData);
			 
			//删除多余的圆点
			circle.exit().remove();
			 
			//圆点初始化，添加圆点,多出来的到右侧底部
			this.group.selectAll("circle").data(arr).enter().append("circle")
				.attr("cx", function(d,i){
					if(i>=olddata.length) return w-padding; else return xScale(i);
				})
				.attr("cy",function(d,i){
					if(i>=olddata.length) return h-foot_height; else return yScale(d);
				})
				.attr("r",5)
				.attr("fill",seriesColors[id % seriesColors.length]);
			 
			this.oldData=arr;
		};
		 
		//重绘加动画效果
		this.reDraw=function(id,_duration)
		{
			var arr=dataset[i];
			var line = d3.svg.line()
				.x(function(d,i){return xScale(i);})
				.y(function(d){return yScale(d);});
			 
			//路径动画
			this.path.transition().duration(_duration).attr("d",line(arr));
			 
			//圆点动画
			this.group.selectAll("circle")
				.transition()
				.duration(_duration)
				.attr("cx", function(d,i) {
					return xScale(i);
				})
				.attr("cy", function(d) {
					return yScale(d);
				})
		};
		 
		//从画布删除折线
		this.remove=function()
		{
			this.group.remove();
		};
	}
	
 	//添加图例
 	function addLegend()
 	{
	 	var textGroup=legend.selectAll("g")
 		.data(seriesNames);
	 	textGroup.exit().remove();
	 	
	 	var lgs = legend.selectAll("g").data(seriesNames).enter().append("g")
		 	.attr("x", function(d,i) {return i*100;})
		 	.attr("y",0);
	 	if (config.udfOptions && config.udfOptions.udfLegend){
	 		config.udfOptions.udfLegend(lgs,symbolTypes,seriesColors);
	 	} else {
	 		lgs.append("rect")
		 	.attr("x", function(d,i) {return i*100-20;})
		 	.attr("y",-10)
		 	.attr("width",12)
		 	.attr("height",12)
		 	.attr("fill",function(d,i){ return seriesColors[i % seriesColors.length];});
	 	}
	 	
	 	lgs.append("text")
		 	.text(function(d){
		 		if(d.length > legendLabelMaxLength) {
		 			d = d.substring(0, legendLabelMaxLength) + "...";
		 		}
		 		return d;
		 	})
		 	.attr("class","gl_legend")
		 	.attr("x", function(d,i) {return i*100;})
		 	.attr("y",0)
		 	.attr("fill", "#333");
	 	
	 	lgs.append("title").text(function(d){return d;});
	 	 
	 	legend.attr("transform","translate("+((w-seriesNames.length*100)/2)+","+ head_height +")");
	}
 	
 	function updateMaxMin(dataset) {
 	 	var mmResult = getMaxdata(dataset);
 	 	if (showRefLine) {
 	 	 	maxXdata = mmResult[0][0] > mmResult[1][0] ? mmResult[0][0]:mmResult[1][0];
 	 	 	minXdata = mmResult[0][1] < mmResult[1][1] ? mmResult[0][1]:mmResult[1][1];
 	 	 	maxYdata = mmResult[0][0] > mmResult[1][0] ? mmResult[0][0]:mmResult[1][0];
 	 	 	minYdata = mmResult[0][1] < mmResult[1][1] ? mmResult[0][1]:mmResult[1][1];
 	 	} else {
 	 		maxXdata = mmResult[0][0];
 	 		minXdata = mmResult[0][1];
 	 	 	maxYdata = mmResult[1][0];
 	 	 	minYdata = mmResult[1][1];
 	 	}
 	 	var xDlt = (maxXdata - minXdata) / 10;
 	 	if(xDlt == 0) {
 	 		xDlt = 1;
 	 	}
 	 	
 	 	maxXLimit = maxXdata + xDlt;
 	 	minXLimit = minXdata - xDlt;
 	 	var yDlt = (maxYdata - minYdata) / 10;
 	 	if(yDlt == 0) {
 	 		yDlt = 10;
 	 	}
 	 	
 	 	maxYLimit = maxYdata + yDlt;
 	 	minYLimit = minYdata - yDlt;
 	}
 	
 	//取得多维数组最大值
 	function getMaxdata(arr)
 	{
 		var mmResult = [[null, null], [null, null]];
 		for(var s = 0; s < mmResult.length; s++) {
 			for(i=0; i < arr.length; i++)
 		 	{
 				var maxdata = mmResult[s][0];
 				var mindata = mmResult[s][1];
 				
 		 		if(maxdata == null) {
 		 			maxdata = d3.max(arr[i], function(d) {return d[s];});
 		 		} else {
 		 			maxdata = d3.max([maxdata, d3.max(arr[i], function(d) {return d[s];})]);
 		 		}
 		 		
 		 		if(mindata == null) {
 		 			mindata = d3.min(arr[i], function(d) {return d[s];});
 		 		} else {
 		 			mindata = d3.min([mindata, d3.min(arr[i], function(d) {return d[s];})]);
 		 		}
 		 		
 		 		mmResult[s][0] = maxdata;
 				mmResult[s][1] = mindata;
 		 	}
 		}
	 	return mmResult;
 	}
}